function setCachePromise(key, data) {
	return new Promise((resolve, reject) => {
		uni.setStorage({
			key: key,
			data: data,
			success: resolve,
			fail: reject,
		});
	});
}

function getCachePromise(key, notError) {
	console.log(key);
	if (notError) {
		return new Promise((resolve) => {
			uni.getStorage({
				key: key,
				success: resolve,
				fail: () => {
					resolve({
						data: null, 
						errMsg: '数据未发现',
					});
				},
			});
		});
	}
	return new Promise((resolve, reject) => {
		uni.getStorage({
			key: key,
			success: resolve,
			fail: reject,
		});
	});
}

function removeCachePromise(key) {
	return new Promise((resolve, reject) => {
		uni.removeStorage({
			key: key,
			success: resolve,
			fail: reject,
		});
	});
}

export function setCache(key, data, expire = 0) {
	return Promise.all(expire > 0 ? [setCachePromise(`${key}-expire`, expire),
		setCachePromise(`${key}-cache-time`, Date.now())] : []).then(() => {
		return setCachePromise(key, data);
	});
}

export function getCache(key, notError = true) {
	return Promise.all([getCachePromise(`${key}-expire`, notError).catch(() => {
		return;
	}),
		getCachePromise(`${key}-cache-time`, notError).catch(() => {
			return;
		})]).then(([expire, time]) => {
		console.warn(expire, time);
		if (expire && time && (time + expire > Date.now())) {
			return removeCachePromise(key);
		}
		return getCachePromise(key, notError).then(({ data, errMsg }) => {
			console.warn(data, errMsg);
			return data;
		});
	});
}

export function removeCache(key) {
	return removeCachePromise(key);
}